import globalDialog from './globalDialog.vue'
import Vue from 'vue'

export function createDialog(options) {
	const defaultOptions = {
		type: 'confirm',
		title: '提示',
		content: '',
		okText: '确定',
		okType: 'primary',
		cancelText: '取消',
		cancelType: 'info',
		width: '50%',
		closeOnClickModal: true,
		closeOnPressEscape: true,
		showClose: true,
		contentComponent: null,
		contentProps: {}
	}
	if (options.type === 'info') {
		defaultOptions.okText = '知道了'
	}
	const propsOptions = Object.assign({}, defaultOptions, options)
	const instance = new Vue({
		data() {
			return {
				isVisible: true,
				confirmLoading: false,
				resolve: null,
				reject: null
			}
		},
		methods: {
			handleOk(data) {
				this.confirmLoading = true
				if (propsOptions.type === 'info') {
					this.resolve({
						data: 'ok'
					})
					this.destroy()
				} else {
					this.resolve({
						data: data || 'ok',
						close: this.destroy
					})
				}
			},
			handleCancel() {
				this.reject({
					data: 'cancel'
				})
				this.destroy()
			},
			destroy() {
				this.confirmLoading = false
				this.isVisible = false
				this.$destroy()
				this.$el.parentNode.removeChild(this.$el)
			}
		},
		render(h) {
			return h(globalDialog, {
				props: {
					...propsOptions,
					isVisible: this.isVisible,
					confirmLoading: this.confirmLoading
				},
				on: {
					ok: this.handleOk,
					cancel: this.handleCancel,
					loadingClose: () => {
						this.confirmLoading = false
					},
					loadingOpen: () => {
						this.confirmLoading = true
					}
				}
			})
		}
	}).$mount()
	document.body.appendChild(instance.$el)
	return new Promise((resolve, reject) => {
		instance.resolve = resolve
		instance.reject = reject
	})
}

